use crate::dto;
use base64::prelude::Engine;
use serde::{Deserialize, Serialize};
use wanmesh_common::net::wireguard;

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EndpointPeerInfo {
    #[serde(flatten)]
    pub inner: dto::core::endpoint_peer::EndpointPeerItem,
    #[serde(flatten)]
    pub inner_endpoint: dto::core::endpoint::Endpoint,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wireguard: Option<dto::endpoint_peer_wireguard_config::EndpointPeerWireguardConfig>,
}

impl EndpointPeerInfo {
    pub fn try_to_wireguard_config(
        &self,
        allowed_ips: Vec<cidr::IpInet>,
    ) -> anyhow::Result<wireguard::config::PeerConfig> {
        let wireguard_config = match &self.wireguard {
            Some(v) => v,
            None => return Err(anyhow::anyhow!("wireguard未设置")),
        };

        let public_key =
            base64::prelude::BASE64_STANDARD.encode(&wireguard_config.config.peer.public_key);
        Ok(wireguard::config::PeerConfig {
            endpoint: wireguard_config.config.peer.inner.endpoint.clone(),
            persistent_keepalive: wireguard_config.config.peer.inner.persistent_keepalive,
            public_key: Some(public_key),
            allowed_ips,
        })
    }
}
